package com.zsh.wanandroid.common;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;

import com.dxq.basic_ui_library.loadSirCallBack.CustomCallback;
import com.dxq.basic_ui_library.loadSirCallBack.EmptyCallback;
import com.dxq.basic_ui_library.loadSirCallBack.ErrorCallback;
import com.dxq.basic_ui_library.loadSirCallBack.LoadingCallback;
import com.dxq.basic_ui_library.loadSirCallBack.TimeoutCallback;
import com.kingja.loadsir.core.LoadSir;
import com.zhouyou.http.EasyHttp;
import com.zsh.wanandroid.api.Api;
import com.zsh.wanandroid.api.ApiService;
import com.zsh.wanandroid.http.AddCookiesInterceptor;
import com.zsh.wanandroid.http.SaveCookiesInterceptor;
import com.zsh.wanandroid.utils.LogUtils;
import com.zsh.wanandroid.utils.OperateLog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author zsh
 * @date 2020/3/11.
 * 功能：application
 */

public class APP extends Application {

    public static String currentAppName = "wanAndroid";
    public static String errorLog = "errorLog";
    public static String operateLog = "operateLog";
    public static String download = "download";
    public static File externalStorageDirectory = Environment.getExternalStorageDirectory();

    //在整个应用执行过程中，需要提供的变量
    public static Context mContext;//需要使用的上下文对象：application实例
    public static Handler mHandler;//需要使用的handler
    public static Thread mainThread;//提供主线程对象
    public static int mainThreadId;//提供主线程对象的id
    public static String errorLogPath = externalStorageDirectory + "/" + currentAppName + "/" + errorLog + "/";//崩溃日志下载路径
    public static String operateLogPath = externalStorageDirectory + "/" + currentAppName + "/" + operateLog + "/";//操作日志下载路径
    public static String versionDownloadPath = externalStorageDirectory + "/" + currentAppName + "/" + download + "/";//版本更新下载路径

    public static ApiService apiService;
    public static String isLogin = "isLogin";

    //1、首先声明一个数组permissions，将需要的权限都放在里面，必须在AndroidManifest.xml文件中设置
    private static String[] PERMISSIONS_STORAGE = {
            //Manifest.permission.READ_PHONE_STATE,//读取手机信息
            Manifest.permission.READ_EXTERNAL_STORAGE,//读文件
            Manifest.permission.WRITE_EXTERNAL_STORAGE,//写文件
            Manifest.permission.ACCESS_FINE_LOCATION,//允许一个程序访问精良位置(如GPS)
            Manifest.permission.ACCESS_COARSE_LOCATION//允许一个程序访问CellID或WiFi热点来获取粗略的位置
    };
    //2、创建一个mPermissionList，逐个判断哪些权限未授予，未授予的权限存储到mPerrrmissionList中
    private static List<String> mPermissionList = new ArrayList<>();
    //3、声明一个请求码，在请求权限的回调方法onRequestPermissionsResult中需要判断使用
    public static final int REQUEST_EXTERNAL_STORAGE = 1000;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this.getApplicationContext();
        mHandler = new Handler();
        mainThread = Thread.currentThread();//实例化当前Application的线程即为主线程
        mainThreadId = android.os.Process.myTid();//获取当前线程的id

        //设置未捕获异常的处理器
        CrashHandler.getInstance().init(mContext);

        //log日志
        LogUtils.setTAG(currentAppName + "_");
        LogUtils.setDebug(true);

        //输出文件日志
        OperateLog.setDebugLevel(6);
        OperateLog.setEnableLog(true);
        OperateLog.setLogPrefix(currentAppName + "_");

        ApplicationProxy.getInstance().setApplication(this);

        initRetrofitHttp();

        initLoadSir();
    }

    private void initRetrofitHttp() {
//        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
//        OkHttpClient client = builder.addInterceptor(new SaveCookiesInterceptor(mContext))
//                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                //.client(client)
                .build();

        apiService = retrofit.create(ApiService.class);
    }

    private void initLoadSir() {
        LoadSir.beginBuilder()
                .addCallback(new ErrorCallback())
                .addCallback(new EmptyCallback())
                .addCallback(new LoadingCallback())
                .addCallback(new TimeoutCallback())
                .addCallback(new CustomCallback())
                .setDefaultCallback(LoadingCallback.class)
                .commit();
    }

    private void initEasyHttp() {
        EasyHttp.init(this);//默认初始化
    }

    //4、进行权限判断和申请（在activity中调用）
    public static void getPermissions(Activity activity) {
        mPermissionList.clear();//清空已经允许的没有通过的权限
        for (int i = 0; i < PERMISSIONS_STORAGE.length; i++) {
            //逐个判断是否还有未通过的权限
            int permission = ActivityCompat.checkSelfPermission(activity, PERMISSIONS_STORAGE[i]);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(PERMISSIONS_STORAGE[i]);
            }
        }
        /**
         * 判断是否为空
         */
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            //delayEntryPage();
            LogUtils.e("已经全部授权");//权限已经都通过了
        } else {//请求权限方法
            LogUtils.e("授权中");//权限已经都通过了
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            //有权限没有通过，需要申请
            ActivityCompat.requestPermissions(activity, permissions, REQUEST_EXTERNAL_STORAGE);
        }
    }

}